﻿var g_vTreatmentStrs=[];
var g_vTreatmentXmlDoc='';
function getTreatmentFlash()
{
    if (typeof(g_vTreatmentFlash)=="undefined") 
    {
        g_vTreatmentFlash="Treatmentchart";
    }
    return g_vTreatmentFlash;
}
function GetTreatmentDegreeColor(iDegreeValue)
{
    return ["#ACD6FF","#3270CF","#D4D4D4","#000040"][iDegreeValue]
}
function GetTreatmentDegreeText(iDegreeValue)
{
    return ["治疗本病","治疗症状","医疗保健","其它"][iDegreeValue]
}
function OnTreatmentFlashReady(id)
{
   //setTimeout("loadTreatmentFlashData('"+id+"')",500);
   loadTreatmentFlashData(id);
}
function CreateTreatmentFlashDegreeText()
{
  var   table = document.createElement('<TABLE>');
  table.style.textAlign="center"; 
  table.style.width="700px"
  table.style.border="1px";
  table.style.backgroundColor="#FFFFFF"
  table.style.borderColor="#dddddd"
  var   tr = table.insertRow(-1);
  for(var i=0;i< 4; ++i)
  {
     var td = tr.insertCell(-1);
     td.style.backgroundColor=GetTreatmentDegreeColor(i);
     td.style.width="6px";
     td.style.borderColor="#dddddd"
     td.innerHTML="&nbsp;"
     td = tr.insertCell(-1);
     td.innerHTML=GetTreatmentDegreeText(i);
     td.style.width="30px"
     td=tr.insertCell(-1);
     td.style.width="20px";
  }
  var flashDiv= _$(getTreatmentFlash()+"1");
  flashDiv.parentNode.insertBefore(table,flashDiv);

}
function formatTreatmentFlashData(startDate,endDate, bForce)//id=0,生成所有的，
{
    g_vTreatmentStrs=[];
    var xResult = g_vTreatmentXmlDoc.getElementsByTagName("result")[0];
    
    var xTreatmentHistories =xResult.getElementsByTagName("treatmenthistories")[0].getElementsByTagName("treatmenthistory");
    if(xTreatmentHistories.length==0)
    {
        var iUin=GetUin();
        var iParamUin=getURLParam("uin",g_sTreatmentUrl);
        if( _$(getTreatmentFlash()+"1") == null ) return false ;       
        if (iUin<=0 || iUin!= iParamUin) _$(getTreatmentFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>该用户尚未添加相关信息</div>";
        else _$(getTreatmentFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>请您<a class='NO_RECORD_CHART_A' href='/Pages/Alpha/SymptomHistory/Index.aspx'>添加</a>相关信息</div>";
        return false;
    }
	printData(1, 10, xTreatmentHistories.length);
    var bgcolor='"bg_colour": "#FFFFFF"';
    var now = parseDate(xResult.getAttribute("now"));
    g_vNow=now;
    var confirmDate = parseDate(xResult.getAttribute("confirmdate"));
    if (typeof(endDate)=="undefined") endDate = now ;
    if(typeof(startDate)=="undefined") {startDate = parseDate(xResult.getAttribute("diseasestart"));bForce=false;}
   
    var startValue = 0 ;
    //format Treatment history        
    var vTreatmentNames=["id","type","desc", "isuse", "startdate","enddate", "purpose","treatmentid","treatmentname","datavalue","unit","limitvalues", "stopreason", "frequence"];
    var vTreatmentHistories=[];
    var vTreatments={};
    var curDate ;
   
    for(var i=0;i<xTreatmentHistories.length;++i) 
    {   
        vTreatmentHistories.push(xml2array(xTreatmentHistories[i],vTreatmentNames));
        var Treatmentid=vTreatmentHistories[i]["treatmentid"];
        var vTreatmentGroup = vTreatments[Treatmentid] ;
        if ( typeof(vTreatmentGroup) == "undefined") 
        {
            vTreatmentGroup = [i];
            vTreatments[Treatmentid] = vTreatmentGroup ;
        }
        else
        {
            vTreatmentGroup.push(i) ;
        }
        
        curDate = parseDate(vTreatmentHistories[i]["startdate"]);
        if (typeof(bForce)=="undefined" || !bForce) 
        {
            if ( curDate<startDate ) startDate = curDate ;
        }
    }
    
    
    //format the xaxis labels
    var xLabels = [];
    var iCur=4;
    var ElementValues={};

    var vXDistance = Math.ceil(distanceDate(startDate,endDate)/(iCur-1.0));//alert("distance:"+distanceDate(startDate,endDate)+"unit:"+vXDistance);
    --iCur;
    curDate = endDate;
    do 
    {
        xLabels[iCur] = curDate.toCommonString();
        startDate = curDate ;	
        curDate = getNextDay(curDate, -vXDistance);
    } while(--iCur >=0 );
    
   
    var xUnit = (distanceDate(startDate, endDate)+0.0)/(xLabels.length-1) ;
    //format the yaxis
    iCur=0;
    {
        //var labChecks = vCharts[chartindex];
        var sTitle='"title":{"text":"'+'","style": "{font-size: 20px;color:#0000ff;font-family:Verdana;text-align:center}"}';
        //format yAxis
        var YAxisLabels=[];
        //对于yaxis
        for(var iTreatmentId in vTreatments)
        {
            ElementValues[iTreatmentId]=[];
        }
        //format Element for each chart
        var vTreatment ;
        var date,nextDate;
        var left,right ;
        iCur=0;
        //format other Treatment
        for(var iTreatmentId in vTreatments)
        {
            YAxisLabels[iCur++] = vTreatmentHistories[vTreatments[iTreatmentId][0]]["treatmentname"];
            var limitValues=vTreatmentHistories[vTreatments[iTreatmentId][0]]["limitvalues"].split("@");
            var aTreatments=vTreatments[iTreatmentId];
            var tmpValues=[];
            for(var k=0; k<aTreatments.length ;++k) 
            {
                var vTreatment=vTreatmentHistories[aTreatments[k]];
                var date=parseDate(vTreatment["startdate"]);
                if(date<startDate) continue ;
                if (date>endDate) break;
                tmpValues.push(parseInt(vTreatment["datavalue"]));
            }
            tmpValues=GetAverageRandArray(tmpValues,8);//alert(tmpValues.join(","))
            for(var k=0; k<aTreatments.length; ++k)
            {
                var vTreatment=vTreatmentHistories[aTreatments[k]];
                var date=parseDate(vTreatment["startdate"]);
                if(date<startDate) continue ;
                if (date>endDate) break;
                var nextDate = parseDate(vTreatment["enddate"]);/*parseDate(vTreatmentHistories[aTreatments[k+1]]["startdate"])*/ 
                if (nextDate>endDate) nextDate = endDate ;
                var left = (distanceDate(startDate,date)/xUnit).toFixed(3) ;
                var right = (distanceDate(startDate,nextDate)/xUnit).toFixed(3) ;
                var height = 0.8*getValueByArray(tmpValues,parseInt(vTreatment["datavalue"]))/(tmpValues.length-1);
                if (height < 0.0001) continue ;
                var sTipText=GetTreatmentDegreeText(vTreatment["purpose"])+vTreatment["datavalue"]+vTreatment["unit"];
                if ("1" == vTreatment["type"]) sTipText = vTreatment["desc"];
                ElementValues[iTreatmentId].push('"left":'+left+',"right":'+right+',"height":'+height+',"colour":"'+GetTreatmentDegreeColor(parseInt(vTreatment["purpose"]))+'","tip":"'+vTreatment["treatmentname"]+":"+sTipText+"<br>"+date.toCommonString()+'--'+nextDate.toCommonString()+'"');   
            }
        }
        var YAxisLabelsLeft=[];
        for(var i=0; i<YAxisLabels.length ;++i) YAxisLabelsLeft[i]="\t";
        var sRightYAxis ='"y_axis_right":{"max":'+(YAxisLabels.length)+',"step":1, "labels":["'+YAxisLabels.join('","')+'",""] },"y2_label_style":"12,#000000","y_label_style":"12,#dddddd"';
        var sYAxis ='"y_axis":{"colour":"#dddddd","max":'+(YAxisLabels.length)+',"step":1, "labels":["'+YAxisLabelsLeft.join('","')+'",""]  }';
        //var sYAxis ='"y_axis":{"offset":20,"max":'+(YAxisLabels.length-1)+',"step":1,"size":25,"colour": "#CF4D5F", "visible":false }';
        var sElementValues=[];
        var iCurTreatment=0;
        //format main Treatment  
        for(var iTreatment in vTreatments)
        {
            sElementValues.push('"type": "hbar", "index":'+sElementValues.length+',"style": "{color: #736AFF;}","values":[{'+ElementValues[iTreatment].join("},{")+'}]');
        }
       
        //set flash height
        _$(getTreatmentFlash()+"1").height=70*sElementValues.length;
        var sXAxis ='"x_axis":{ "max":'+(xLabels.length-1)+',"labels":{"rotate":0,"labels":["'+xLabels.join('","')+'"]}}';
        var sElements='"elements":[{'+sElementValues.join('},{')+'}]';
        var sHoverTip='"tooltip": { "mouse": 2, "stroke": 1, "colour": "#000000", "background": "#ffffff" }'
        g_vTreatmentStrs.push('{'+sTitle+','+sXAxis+','+sYAxis+','+sRightYAxis+','+sElements+','+bgcolor+','+sHoverTip+'}');
    }
    return true ;
}
function showTreatmentFlash(id)
{
    var tmp = _$(getTreatmentFlash()+id); 
    try{tmp.load(g_vTreatmentStrs[id-1]);}
    catch(e){}
    
    //document.write(g_vTreatmentStrs[id-1]);
}
function loadTreatmentFlashData(id)
{	
	function OnSucc(xmlDoc)
    { 
        g_vTreatmentXmlDoc = xmlDoc ;
        if(!formatTreatmentFlashData()) return ;
        showTreatmentFlash(id);
        CreateTreatmentFlashDegreeText();
        if (typeof(g_chartwidth)=="undefined") g_chartwidth=720;
        for(var iCur=2; iCur<=g_vTreatmentStrs.length;++iCur)
            swfobject.embedSWF("/support/swfchart/open-flash-chart.swf", getTreatmentFlash()+(iCur), g_chartwidth+'', "350","9.0.0", "expressInstall.swf",{'id':''+iCur});
        
    }
    
    function OnFail(xmlDoc)
    {
        alert("获取数据失败");
    }
    if (id == 1)
    {
        if (typeof(g_sTreatmentUrl)=="undefined") g_sTreatmentUrl = "/Pages/Alpha/TreatmentHistory/TreatmentHistory.aspx";
        getResultXml(g_sTreatmentUrl,OnSucc,OnFail,OnFail);
    }
    else if (id <= g_vTreatmentStrs.length) 
    {
          var tmp = _$("Treatmentchart"+id); 
          showTreatmentFlash(id);
    }
}
function showTreatmentFlashMode(i,dStart,dEnd)
{
    var enddate = g_vNow;
    var startdate;
    switch(i)
    {
        case 1:startdate = getPreBeginMonthDate(enddate,3);break;
        case 2:startdate = getPreBeginMonthDate(enddate,6);break;
        case 3:startdate = getPreBeginMonthDate(enddate,12);break;
        case 4:startdate = getPreBeginMonthDate(enddate,36);break;
        case 5:
            startdate = dStart < dEnd ?　dStart : dEnd ;
            enddate = dStart  > dEnd ?　dStart : dEnd ;
            if (startdate==enddate) 
            {
                alert("起始日期和终止日期相同");
                return ;
            }
        default:break;
    } 
    if (!formatTreatmentFlashData(startdate,enddate, true)) return ;
    showTreatmentFlash(1);
}
function printData(iPageNo, iPageNum, iTotal)
{
    var oParent = _$("treatment_list");
    if (oParent==null) return ;
    var xResult=g_vTreatmentXmlDoc.getElementsByTagName("result")[0];
	var sHtml = document.body.innerHTML.between("<!--TP.LIST","TP.LIST-->");
	var mapStopReasons={0:"疗效不佳", 1:"疗程结束", 2:"不良反应", 3:"价格太贵", 4:"其它"};
	var mapPurposes={ 0:"治疗本病", 1:"治疗症状", 2:"医疗保健", 3:"其它或不清楚"};
	var mapName=[
			['id','<%id%>'],
			['startdate','<%startdate%>', function(v){ return parseDate(v).toCommonString()}],
			['enddate','<%enddate%>', function(v){ return parseDate(v).toCommonString()}],
			['datavalue','<%datavalue%>'],
			['unit','<%measurementunit%>'],
			['frequence','<%frequency%>', function(v){ return v.escHtml()}],
			['purpose','<%userpurpose%>', function(v){return mapPurposes[v].escHtml()}],
			['stopreason','<%stopreason%>', function(v){return mapStopReasons[v].escHtml()}]
			];
	var iStart = (iPageNo-1)*iPageNum ;
	var iEnd   = iStart + iPageNum ;
	iEnd = iEnd > iTotal ? iTotal : iEnd;
	
	showXmlNode(xResult, oParent, "treatmenthistory",sHtml, mapName, iStart, iEnd);
   
    iTotalPageNum = Math.ceil(iTotal/iPageNum);      
    showPage(iPageNo,iTotalPageNum,function(n){return "javascript:printData("+n+","+iPageNum+","+iTotal+");";},document.getElementById("ID_page"),0);
}

